﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Definitions;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Profiles.Controls
{
    public class BlogEditControl : UserControl
    {
        protected TextBox blogNameField;
        protected TextBox blogUrlField;
        protected TextBox rssUrlField;
        protected TextBox descriptionField;
        protected TextBox firstEntryField;
        protected Button saveButton;

        private Common.Dto.BlogDto _item;

        protected Common.Dto.BlogDto Item
        {
            get
            {
                if (_item != null)
                    return _item;

                var id = Helper.GetIdFromQueryString(Request.QueryString["blogID"]);
                if (id == 0)
                    return null;

                var rep = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
                _item = rep.GetBlogById(id);
                return _item;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            saveButton.Click += SaveButtonClick;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var currentUser = SPContext.Current.Web.CurrentUser;
            var redirectUrl = "/_layouts/Eneta.Portal.Authentication/LiveAuthHandler.aspx?action=login";

            if (currentUser == null)
            {
                Response.Redirect(redirectUrl);
                return;
            }

            if (Item != null)
            {
                if (string.IsNullOrEmpty(Item.OwnerUserName))
                {
                    Response.Redirect(redirectUrl);
                    return;
                }

                if (Item.OwnerUserName != currentUser.LoginName)
                    if (!currentUser.IsSiteAdmin)
                    {
                        Response.Redirect("/");
                        return;
                    }
            }

            descriptionField.Attributes.Add("onKeyDown", "return textCounter(this,event)");
            descriptionField.Attributes.Add("onKeyUp", "return textCounter(this,event)");

            if (IsPostBack)
                return;

            if (Item == null)
                return;

            blogNameField.Text = Item.Title;
            blogUrlField.Text = Item.Url;

            descriptionField.Text = Item.Description;

            if (Item.FirstEntryDate != DateTime.MinValue)
            {
                firstEntryField.CssClass = "text-go";
                firstEntryField.Text = Item.FirstEntryDate.ToString("dd.MM.yyyy");
            }
            else
            {
                firstEntryField.CssClass = "text-go clear";
                firstEntryField.Text = "pp.kk.aaaa";
            }
            Page.Title = Resources.GetResourceString("AddBlog") + " | Microsoft Eneta";
            rssUrlField.Text = Item.RssUrl;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "descrField", "<script>var descrFieldId='" + descriptionField.ClientID + "';</script>");
        }

        protected void SaveButtonClick(object sender, EventArgs e)
        {
            if (SPContext.Current.Web.CurrentUser == null)
            {
                Logger.LogInfo("SaveButtonClick(): Session expired");
                Response.Redirect("/");
                Response.End();
            }
            var errors = new Dictionary<string, string>();

            if (string.IsNullOrEmpty(blogNameField.Text))
            {
                errors.Add("blogName", Resources.GetResourceString("BlogNameIsRequired"));
            }
            else if (blogNameField.Text.Length > 255)
            {
                errors.Add("blogName", Resources.GetResourceString("BlogNameIsTooLong"));
            }

            if (string.IsNullOrEmpty(blogUrlField.Text))
            {
                errors.Add("blogUrl", Resources.GetResourceString("BlogUrlIsRequired"));
            }
            else if (blogUrlField.Text.Length > 255)
            {
                errors.Add("blogUrl", Resources.GetResourceString("BlogUrlIsTooLong"));
            }

            if (string.IsNullOrEmpty(rssUrlField.Text))
            {
                errors.Add("rssUrl", Resources.GetResourceString("RssUrlIsRequired"));
            }
            else if (rssUrlField.Text.Length > 255)
            {
                errors.Add("rssUrl", Resources.GetResourceString("RssUrlIsTooLong"));
            }

            if (string.IsNullOrEmpty(descriptionField.Text))
            {
                errors.Add("description", Resources.GetResourceString("BlogDescriptionIsRequired"));
            }
            else if (descriptionField.Text.Length > 255)
            {
                errors.Add("description", Resources.GetResourceString("BlogDescriptionIsTooLong"));
            }

            var date = DateTime.Now;
            if (string.IsNullOrEmpty(firstEntryField.Text))
            {
                errors.Add("firstEntry", Resources.GetResourceString("FirstEntryDateIsRequired"));
            }
            else if (!DateTime.TryParse(firstEntryField.Text, out date))
            {
                errors.Add("firstEntry", Resources.GetResourceString("FirstEntryDateIsIncorrect"));
            }

            if (errors.Count > 0)
            {
                ApplyErrors(errors);
                return;
            }

            if (Item == null)
            {
                var dto = new BlogDto();
                dto.Title = blogNameField.Text;
                dto.Url = blogUrlField.Text;
                dto.RssUrl = rssUrlField.Text;
                dto.Description = descriptionField.Text;
                dto.FirstEntryDate = date;
                dto.OwnerUserName = SPContext.Current.Web.CurrentUser.LoginName;

                var repository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
                repository.SaveBlog(dto);

                try
                {
                    var currentUser = SPContext.Current.Web.CurrentUser;
                    var userMail = currentUser.Email;

                    var mailer = new MailerService();
                    var addresses = new[] { userMail, "abi@eneta.ee" };
                    mailer.SendMailByTemplate("BlogAdded", currentUser.Name, blogNameField.Text, null, addresses);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                }
            }
            else
            {
                var sec = new SPSecurity.CodeToRunElevated(delegate
                {
                    var siteId = SPContext.Current.Web.Site.Url;
                    using (var site = new SPSite(siteId))
                    using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalBlogSiteUrl)))
                    {
                        var pubWeb = PublishingWeb.GetPublishingWeb(web);
                        var list = pubWeb.PagesList;
                        var item = list.GetItemById(Item.ID);
                        var prevTitle = item.Title;
                        var status = item.ModerationInformation.Status;

                        if (item.File.CheckOutType == SPFile.SPCheckOutType.None)
                            item.File.CheckOut();

                        item[BlogFields.Title] = blogNameField.Text;

                        var url = new SPFieldUrlValue();
                        url.Url = blogUrlField.Text;
                        item[BlogFields.Url] = url;

                        item[BlogFields.Description] = descriptionField.Text;
                        item[BlogFields.FirstEntryDate] = DateTime.Parse(firstEntryField.Text);

                        var rssUrlValue = new SPFieldUrlValue();
                        rssUrlValue.Url = rssUrlField.Text;
                        item[BlogFields.RssUrl] = rssUrlValue;
                        item.Update();

                        item.File.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);

                        if (status == SPModerationStatusType.Approved)
                            item.File.Approve(string.Empty);
                        else
                            item.File.Publish(string.Empty);

                        var newPageName = UrlHelper.GetPageFileName(blogNameField.Text);
                        if (prevTitle.ToLower() != blogNameField.Text.ToLower()) 
                            item.File.MoveTo(item.ParentList.RootFolder.Url + "/" + newPageName);
                    }
                });
                SPSecurity.RunWithElevatedPrivileges(sec);

                // Kinnita ära ka
            }
            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var user = SPContext.Current.Web.CurrentUser;
            var profile = profileRepository.GetUserProfileByUserName(user.LoginName); 
            if (Item == null)
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profile.Id + "&msg=blogadd", false);
            else
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profile.Id + "&msg=blogsave", false);
        }

        private void ApplyErrors(Dictionary<string, string> errors)
        {
            foreach (string fieldKey in errors.Keys)
            {
                var error = errors[fieldKey];
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl != null)
                    ctl.Attributes.Add("class", "info-row failed-info");

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl != null)
                    ctl.Visible = true;

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl != null)
                    ctl.InnerText = error;
            }
        }

        protected string GetWebUrl(SPSite site, string webUrl)
        {
            webUrl = webUrl.ToLower().Replace(site.Url.ToLower(), string.Empty);
            if (!string.IsNullOrEmpty(site.Url))
                if (!webUrl.StartsWith("/"))
                    webUrl = "/" + webUrl;
            Logger.LogInfo("SITE URL: " + site.Url);
            Logger.LogInfo("WEB URL: " + webUrl);
            return webUrl;
        }
    }
}
